import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/phoenix/information/api/information_api.dart';
import 'package:dk_flutter_module_sale/phoenix/information/bean/bean_information.dart';
import 'package:dk_flutter_module_sale/r.dart';
import 'package:flutter/material.dart';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/phoenix/information/bean/ut_informaiton.dart';

class InformationListPage extends CommonPage {
  final String categoryId;
  InformationListPage(this.categoryId);

  @override
  void onInitState(CommonPageBloc pageBloc) {
    Map<String, dynamic> paramsMap = Map();
    paramsMap["pageNum"] = 1;
    paramsMap["categoryId"] = categoryId;
    pageBloc.pageHttpPost(
        path: InformationApi.informationList,
        data: paramsMap,
        widgetBuilderByData: (dynamic data) {
          BeanInformation beanInformation =
              BeanInformation.fromJson(data) ?? BeanInformation();
          return InformationList(beanInformation, paramsMap, pageBloc);
        });
  }
}

class InformationList extends StatefulWidget {
  final BeanInformation beanInformation;
  final Map<String, dynamic> paramsMap;
  final CommonPageBloc pageBloc;

  InformationList(this.beanInformation, this.paramsMap, this.pageBloc);
  @override
  State<StatefulWidget> createState() {
    return _InformationListState(beanInformation);
  }
}

class _InformationListState extends State<InformationList>
    with AutomaticKeepAliveClientMixin {
  BeanInformation beanInformation;
  int cpageIndex;
  int cpageTotal;
  DkEasyRefreshController easyRefreshController;
  _InformationListState(this.beanInformation);

  @override
  void initState() {
    super.initState();
    easyRefreshController = DkEasyRefreshController();
    cpageIndex = beanInformation.currentPage;
    cpageTotal = beanInformation.totalPage;
  }

  Future<void> refreshPage() async {
    this.cpageIndex = 1;
    widget.paramsMap['pageNum'] = this.cpageIndex;
    widget.pageBloc.dataHttpPost(
        path: InformationApi.informationList,
        data: widget.paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            this.beanInformation =
                BeanInformation.fromJson(data) ?? BeanInformation();
            easyRefreshController.finishRefresh(success: true);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishRefresh(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishRefresh(success: false);
        });
  }

  Future<void> loadMore() async {
    widget.paramsMap['pageNum'] = (++this.cpageIndex);
    widget.pageBloc.dataHttpPost(
        path: InformationApi.informationList,
        data: widget.paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            BeanInformation addDataBean =
                BeanInformation.fromJson(data) ?? BeanInformation();
            ;
            this.beanInformation.list.addAll(addDataBean.list);
            easyRefreshController.finishLoad(
                success: true,
                noMore: this.cpageIndex >= addDataBean.totalPage);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    bool noMore = this.cpageIndex >= this.beanInformation.totalPage;
    return Container(
      color: Colors.white,
      child: DkRefreshListWidget.custom(
          controller: easyRefreshController,
          onLoad: noMore ? null : this.loadMore,
          onRefresh: this.refreshPage,
          emptyWidget: this.beanInformation.list.length == 0
              ? LogicPage(PortalConfig.smallEmptyPageParam)
              : null,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  if (index < beanInformation.list.length) {
                    return getItemCell(beanInformation.list[index],
                        index != beanInformation.list.length - 1);
                  } else {
                    return null;
                  }
                },
                childCount: this.beanInformation.list.length,
              ),
            ),
          ]),
    );
  }

  Widget getItemCell(ListItemBean listItemBean, bool showDivider) {
    String defaultIcon = R.imagesPortalInformationEmptyPng;
    return GestureDetector(
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.white,
              height: 122,
              padding: EdgeInsets.fromLTRB(16, 17, 16, 15.4),
              child: Row(
                //crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 135,
                    height: 89.6,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(5),
                      child: CachedNetworkImage(
                        imageUrl: listItemBean.iconUrl,
                        placeholder: (context, url) => Image.asset(defaultIcon),
                        errorWidget: (context, url, error) =>
                            Image.asset(defaultIcon),
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            width: 196,
                            child: Text(
                              listItemBean.title,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 16,
                                color: Color(0xff333333),
                              ),
                            ),
                          ),
                        ),
                        Container(
                          child: Text(
                            listItemBean.time,
                            maxLines: 1,
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0xff999999),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            showDivider
                ? DkDivider(DividerOption.horizontal(
                    indentEnd: 0, indentStart: 16, height: 1))
                : Container(),
          ],
        ),
        onTap: () {
          RouteUtil.goPage(listItemBean.appRouteUrl);
          UserTrack.track(
              InformationUt.informationClickItem, {"name": listItemBean.title});
        });
  }

  @override
  bool get wantKeepAlive => true;
}
